package com.raidroid.rdmute;

import java.util.HashMap;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.IBinder;
import android.os.Vibrator;

public class RDMuteService extends Service implements SensorEventListener{

	public static boolean IsServiceRunning = false;
	public static boolean IsTaskBarNotificationsOn = false;	
	public static boolean IsHapticFeedbackOn = false;
	public static boolean IsSoundFeedbackOn = false;
	
	public static int ROLL_LOVER = -25;
	public static int ROLL_UPER = 25;
	public static int PITCH_LOVER = -160;
	public static int PITCH_UPER = 160;
	public static int SEEKBAR_PROGRESS = 10;
	public static int SENSIVITY = 0;
	public static final int SOUND_NOTIFICATION = 1;
	public static int VIBRATORDURATION = 50;
	
	private SoundPool soundPool;
	private HashMap<Integer, Integer> soundPoolMap; 
	private SensorManager sensorMan = null;
	private float PITCH;
	private float ROLL;
	private boolean IsWorked = false;
	private boolean IsVibrate = false;
	
	@Override
    public void onCreate() {
          super.onCreate();
          IsServiceRunning = true;
          
          //ReadingPreferences          
          SharedPreferences sp = getSharedPreferences("com.raidroid.rdmute_preferences", MODE_PRIVATE);
          SEEKBAR_PROGRESS = sp.getInt("RDMute_Sensivity", 10);
          IsTaskBarNotificationsOn = sp.getBoolean("RDMute_Notifications_OnOf", false);
          IsHapticFeedbackOn = sp.getBoolean("RdMute_HapticFeedback_OnOf", false);
          IsSoundFeedbackOn = sp.getBoolean("RDMute_AudioFeedback_OnOf", false);
                    
          sensorMan = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
          sensorMan.registerListener(this, 
          		sensorMan.getDefaultSensor(Sensor.TYPE_ORIENTATION),
                  SensorManager.SENSOR_DELAY_UI);
          
          soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 100);
          soundPoolMap = new HashMap<Integer, Integer>();
          soundPoolMap.put(SOUND_NOTIFICATION, soundPool.load(this, R.raw.notificationsound, 1)); 
    }
	
    @Override
    public void onDestroy() {
    	  IsServiceRunning = false;
    	  sensorMan.unregisterListener(this);	
          super.onDestroy();
    }
	
	@Override
	public IBinder onBind(Intent intent) {		
		IsServiceRunning = true;
		
		//ReadingPreferences          
        SharedPreferences sp = getSharedPreferences("com.raidroid.rdmute_preferences", MODE_PRIVATE);
        SEEKBAR_PROGRESS = sp.getInt("RDMute_Sensivity", 10);
        IsTaskBarNotificationsOn = sp.getBoolean("RDMute_Notifications_OnOf", false);
        IsHapticFeedbackOn = sp.getBoolean("RdMute_HapticFeedback_OnOf", false);
        IsSoundFeedbackOn = sp.getBoolean("RDMute_AudioFeedback_OnOf", false);
		
		return null;
	}

	public void onAccuracyChanged(Sensor sensor, int accuracy) {
		// TODO Auto-generated method stub		
	}

	public void onSensorChanged(SensorEvent event) {
		float vals[] = event.values;
        PITCH = vals[1];//Pitch
        ROLL = vals[2];//Roll		
        
//        Log.d("RD Mute Service", "PITCH : " + PITCH);
//        Log.d("RD Mute Service", "ROLL : " + ROLL);
        
        int nPITCH_UPER = PITCH_UPER;
        int nPITCH_LOVER = PITCH_LOVER;
        int nROLL_UPER = ROLL_UPER;
        int nROLL_LOVER = ROLL_LOVER;
        
        if(SENSIVITY != 0){
	        nPITCH_UPER = PITCH_UPER - SENSIVITY;
	        nPITCH_LOVER = PITCH_LOVER + SENSIVITY;        
	        nROLL_UPER = ROLL_UPER + SENSIVITY;
	        nROLL_LOVER = ROLL_LOVER - SENSIVITY;
        }
        
//        Log.d("RD Mute Service", "nPITCH_UPER : " + nPITCH_UPER);
//        Log.d("RD Mute Service", "nPITCH_LOVER : " + nPITCH_LOVER);
//        Log.d("RD Mute Service", "nROLL_UPER : " + nROLL_UPER);
//        Log.d("RD Mute Service", "nROLL_LOVER : " + nROLL_LOVER);
        
        if(PITCH > nPITCH_UPER || PITCH < nPITCH_LOVER){
    	   if(ROLL < nROLL_UPER && ROLL > nROLL_LOVER){  
    		   AudioManager am = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
    		   if(am.getRingerMode() == AudioManager.RINGER_MODE_NORMAL){
    			  
    			   //Haptic Feedback
    			   if(IsHapticFeedbackOn){
    				   ((Vibrator)getSystemService(VIBRATOR_SERVICE)).vibrate(VIBRATORDURATION);
    			   }
    			   //Sound Feedback
     			   if(IsSoundFeedbackOn){
     				   playSoundFeedback();
     			   }
    			   
    			   am.setRingerMode(AudioManager.RINGER_MODE_SILENT);
    			   //Notification
    			   if(IsTaskBarNotificationsOn){
    				   createNotification("RD Mute", "RD Mute Message", "Sound is OFF", 3, R.drawable.sound_mute);
    			   }
    			   IsWorked = true;
    		   }else if(am.getRingerMode() == AudioManager.RINGER_MODE_VIBRATE){
    			   IsVibrate = true;
    			   
    			   //Haptic Feedback
    			   if(IsHapticFeedbackOn){
    				   ((Vibrator)getSystemService(VIBRATOR_SERVICE)).vibrate(VIBRATORDURATION);
    			   }
    			   //Sound Feedback
     			   if(IsSoundFeedbackOn){
     				   playSoundFeedback();
     			   }
    			   
    			   am.setRingerMode(AudioManager.RINGER_MODE_SILENT);
    			   //Notification
    			   if(IsTaskBarNotificationsOn){
    				   createNotification("RD Mute", "RD Mute Message", "Sound is OFF", 3, R.drawable.sound_mute);
    			   }
    			   IsWorked = true;
    		   }
    	   }else if(PITCH > nPITCH_UPER || PITCH < nPITCH_LOVER){
    		   AudioManager am = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
    		    if(IsWorked){
	     		    if(am.getRingerMode() == AudioManager.RINGER_MODE_SILENT){
	     		    	
	     		    	if(!IsVibrate){
	     		    		am.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
	     		    	}else{
	     		    		am.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
	     		    	}
	     		    	//Notification
	     			    if(IsTaskBarNotificationsOn){
	     			    	createNotification("RD Mute", "RD Mute Message", "Sound is ON", 2, R.drawable.sound);
	     			    }	     			    
	     			   //Haptic Feedback
	     			   if(IsHapticFeedbackOn){
	     				   ((Vibrator)getSystemService(VIBRATOR_SERVICE)).vibrate(VIBRATORDURATION);
	     			   }
	     			   //Sound Feedback
	     			   if(IsSoundFeedbackOn){
	     				   playSoundFeedback();
	     			   }

	     			   IsWorked = false;
	     			   IsVibrate = false;
	     		    }
    		    }
    	   }		    	   
        }else{
        	if(ROLL < nROLL_UPER && ROLL > nROLL_LOVER){
     		    AudioManager am = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
     		    if(IsWorked){
	     		    if(am.getRingerMode() == AudioManager.RINGER_MODE_SILENT){	     		    	
	     		    	if(!IsVibrate){
	     		    		am.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
	     		    	}else{
	     		    		am.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
	     		    	}
	     		    	
	     		       //Notification
	     			   if(IsTaskBarNotificationsOn){
	     				   createNotification("RD Mute", "RD Mute Message", "Sound is ON", 2, R.drawable.sound);
	     			   }
	     		       //Haptic Feedback
	     			   if(IsHapticFeedbackOn){
	     				   ((Vibrator)getSystemService(VIBRATOR_SERVICE)).vibrate(VIBRATORDURATION);
	     			   }	     			   
	     			   //Sound Feedback
	     			   if(IsSoundFeedbackOn){
	     				   playSoundFeedback();
	     			   }
	     			   	     			   
	     			   IsWorked = false;
	     			   IsVibrate = false;
	     		    }
     		    }
        	}
        }		
	}
	
	public static void setSensivity(int sensivity){
//		Log.d("RD Mute Service", "SENSIVITY : " + sensivity);
		SENSIVITY = sensivity -10;
//		Log.d("RD Mute Service", "SENSIVITY NEW : " + SENSIVITY);
	}
	
	public void playSoundFeedback(){
		AudioManager mgr = (AudioManager)this.getSystemService(Context.AUDIO_SERVICE);
	    int soundVolume = mgr.getStreamVolume(AudioManager.STREAM_NOTIFICATION); 
		soundPool.play(SOUND_NOTIFICATION, soundVolume, soundVolume, 1, 0, 1f);
	}
	
	private void createNotification(String _tickerText, String _contentTitle, String _contentText, int notifyID, int notificationIcon){	    	
    	String ns = Context.NOTIFICATION_SERVICE;
    	NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
    	
    	int icon = notificationIcon;
        CharSequence tickerText = _tickerText;      
        long when = System.currentTimeMillis(); 
        Context context = getApplicationContext();
        CharSequence contentTitle = _contentTitle;
        CharSequence contentText = _contentText;    

        Intent notificationIntent = new Intent(this, RDMute.class);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

        Notification notification = new Notification(icon, tickerText, when);
        notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
        
        final int RDMUTE_NOTIFY_ID = notifyID;
        mNotificationManager.notify(RDMUTE_NOTIFY_ID, notification);
	}

}
